import java.util.Iterator;

import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodNode;

import com.rshacking.rhf.files.ClassContainer;
import com.rshacking.rhf.updater.Transform;
import com.rshacking.rhf.updater.hooks.ClassHook;
import com.rshacking.rhf.updater.hooks.HooksList;
import com.rshacking.rhf.updater.instructions.InsnCondition;
import com.rshacking.rhf.updater.instructions.InstructionFinder;

public class ClientTransforms extends Transform {

	@Override
	public boolean canActivate(HooksList hooks, ClassContainer cc) {
		return cc.getName().equals("client");
	}

	@Override
	public boolean execute(HooksList hooks, ClassContainer cc) {
		ClassHook c = null;
		if (hooks.contains("Client"))
			c = hooks.get("Client");
		else
			c = hooks.add("Client", "client");

		Iterator<MethodNode> methods = cc.getASM().methods.iterator();
		while (methods.hasNext()) {
			MethodNode method = methods.next();

			if (method.desc.equals("(B)Ljava/lang/String;")) {
				InstructionFinder<AbstractInsnNode> finder = new InstructionFinder<AbstractInsnNode>(
						method, true);
				FieldInsnNode fin = null;

				fin = (FieldInsnNode) finder
						.getNext(InsnCondition.ASM.GETSTATIC_L);

				if (fin != null) {
					c.add("localPlayer", fin);

				}

				finder.reset(true);
				finder.getNext(InsnCondition.ASM.makeLDCCond("[1)"));

				fin = (FieldInsnNode) finder
						.getNext(InsnCondition.ASM.GETSTATIC_I);
				if (fin != null) {
					c.add("baseX", fin);
				}

				fin = (FieldInsnNode) finder
						.getNext(InsnCondition.ASM.GETSTATIC_I);
				if (fin != null) {
					c.add("baseY", fin);
				}

				finder.getNext(InsnCondition.ASM.makeLDCCond("14)"));
				fin = (FieldInsnNode) finder
						.getNext(InsnCondition.ASM.GETSTATIC_I);
				if (fin != null) {
					c.add("loginIndex", fin);
				}
				return true;
			}
		}
		return false;
	}
}